package gw.com.android.presenter.http;

import android.text.TextUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import gw.com.android.app.AppMain;
import gw.com.android.model.ConfigType;
import gw.com.android.model.ConfigUtil;
import gw.com.android.utils.ThreadPool;
import okhttp3.Response;
import www.com.library.app.Logger;

/**
 * @author jett
 * @since 2017-11-22.
 */
public class JiepanRequest {

    private final String TAG = "JiepanRequest";
    private OnJiepanListener listener;
    private boolean requesting = false;

    public void getCourse() {
        if (requesting) {
            Logger.i(TAG, "a request is already running now...");
            return;
        }
        requesting = true;
        ThreadPool.getInstance().submit(new Runnable() {
            @Override
            public void run() {
                Logger.i(TAG, "begin request");
                call();
                requesting = false;
                Logger.i(TAG, "end request");
            }
        });
    }

    public void setListener(OnJiepanListener listener) {
        this.listener = listener;
    }

    private void call() {
        try {
            Response response = requestCourse("S");
            Logger.i(TAG, "get isNext course response.");
            if (response != null && response.isSuccessful()) {
                String str = response.body().string();
                CourseData courseData = parseCourse(str);
                if (courseData == null) {
                    Logger.i(TAG, "isNext course is empty,requst next course");
                    response = requestCourse("SN");
                    if (response != null && response.isSuccessful()) {
                        str = response.body().string();
                        courseData = parseCourse(str);
                        if (courseData != null && listener != null) {
                            Logger.i(TAG, "send next course and begin request teacher");
                            courseData.isNext = true;
                            sendCourseData(courseData);
                            requestTeacher(courseData.lecturerId, 0);
                            return;
                        }
                    }
                } else {
                    Logger.i(TAG, "send isNext course and begin request teacher");
                    sendCourseData(courseData);
                    requestTeacher(courseData.lecturerId, 0);
                    return;
                }
            }
        } catch (Exception e) {
            Logger.e(TAG, e);
        }
        sendFailure();
    }

    private CourseData parseCourse(String str) {
        if (!TextUtils.isEmpty(str)) {
            try {
                JSONObject jsonObject = new JSONObject(str);
                JSONArray dataArr = jsonObject.optJSONArray("data");
                if (dataArr != null && dataArr.length() > 0) {
                    JSONObject json = dataArr.optJSONObject(0);
                    if (json != null) {
                        CourseData data = new CourseData();
                        data.title = json.optString("title");
                        data.lecturer = json.optString("lecturer");
                        data.lecturerId = json.optString("lecturerId");
                        data.date = json.optString("date");
                        data.startTime = json.optString("startTime");
                        data.endTime = json.optString("endTime");
                        data.isNext = json.optBoolean("isNext", false);
                        return data;
                    }
                }
            } catch (JSONException e) {
                Logger.e(TAG, e);
            }
        }
        return null;
    }

    private Response requestCourse(String flag) throws IOException {
        String url = ConfigUtil.instance().getHttpUrlIp(ConfigType.CHAT_URL_TAG) + "/api/common/getCourse";
        return new Https().url(url)
                .addParam("type", "hx")//事业部标识，pm/fx/hx
                .addParam("platform", "app")//平台 pm(web24k,webui,app,pc)/fx(gwfx,uce,webui)/hx(uce,webui)
                .addParam("groupType", ConfigUtil.instance().mConfigObject.optString(ConfigType.CHAT_GROUP_TYPE))
                .addParam("groupId", ConfigUtil.instance().mConfigObject.optString(ConfigType.CHAT_GROUP_ID))
                .addParam("flag", flag)//获取课程安排标识 S(正在直播的课程)/SN(下次课程安排)/D(全天课程安排)/W(一周课程安排
                .addParam("systemCategory", "hx")
                .get();
    }

    private void requestTeacher(String lecturerId, int counter) throws IOException {
        if (counter >= 3) {
            Logger.i(TAG, "out of count, count = " + counter);
            return;
        }
        ChatTokenRequest tokenRequest = new ChatTokenRequest();
        String token = tokenRequest.acquire();
        if (TextUtils.isEmpty(token)) {
            Logger.i(TAG, "request token is empty......,exit");
            return;
        }
        String url = ConfigUtil.instance().getHttpUrlIp(ConfigType.CHAT_URL_TAG) + "/api/user/getUserInfoByUserNo";
        Response response = new Https().url(url)
                .addParam("userNo", lecturerId)
                .addParam("token", token)
                .addParam("appsecret", ConfigUtil.instance().mConfigObject.optString(ConfigType.CHAT_APPSECRET))
                .addParam("systemCategory", "hx")
                .get();
        if (response == null || !response.isSuccessful()) {
            Logger.i(TAG, "request teacher failed, code = " + (response == null ? -1 : response.code()));
            return;
        }
        String str = response.body().string();
        try {
            JSONObject jsonObject = new JSONObject(str);
            String result = jsonObject.optString("result");
            if ("5002".equals(result)) {
                Logger.i(TAG, "request teacher ,token is expired,clear local token and resend request..");
                // 5002  {"result":"5002","msg":"Token信息已经过期，请重新申请！"}
                tokenRequest.clearLocalToken();
                requestTeacher(lecturerId, ++counter);
                return;
            }
            JSONObject dataJson = jsonObject.optJSONObject("data");
            if (dataJson != null) {
                TeacherData teacherData = new TeacherData();
                teacherData.userNo = dataJson.optString("userNo");
                teacherData.position = dataJson.optString("position");
                teacherData.winRate = dataJson.optString("winRate");
                teacherData.avatar = dataJson.optString("avatar");
                Logger.i(TAG, "send teacher data");
                sendTeacherData(teacherData);
            }
        } catch (JSONException e) {
            Logger.e(TAG, e);
        }
    }

    private void sendCourseData(final CourseData course) {
        if (listener == null) {
            return;
        }
        AppMain.getApp().getHandler().post(new Runnable() {
            @Override
            public void run() {
                if (listener != null) {
                    listener.onCourse(course);
                }
            }
        });
    }

    private void sendTeacherData(final TeacherData teacher) {
        if (listener == null) {
            return;
        }
        AppMain.getApp().getHandler().post(new Runnable() {
            @Override
            public void run() {
                if (listener != null) {
                    listener.onTeacher(teacher);
                }
            }
        });
    }

    private void sendFailure() {
        if (listener == null) {
            return;
        }
        AppMain.getApp().getHandler().post(new Runnable() {
            @Override
            public void run() {
                if (listener != null) {
                    listener.onFailure();
                }
            }
        });
    }

    public class CourseData {
        public boolean isNext;
        public String title;
        public String lecturer;
        public String lecturerId;
        public String date;
        public String startTime;
        public String endTime;
    }

    public class TeacherData {
        public String userNo;
        public String position;
        public String winRate;
        public String avatar;
    }

    public interface OnJiepanListener {

        void onCourse(CourseData course);

        void onTeacher(TeacherData teacher);

        void onFailure();

    }

}
